using Domain.Entities;
using Domain.Permissions;
using Domain.Services;
using ServerControls.ImageLink;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using UserInterface.Misc;

namespace UserInterface
{
    public partial class ViewForum : BoardPageBase
    {
        protected short forumId;
        private string currentTemplate;

        protected void Page_Load(object sender, EventArgs e)
        {
            forumId = Convert.ToInt16(Request.QueryString["forumId"]);
            string pageTitle = (string)GetLocalResourceObject("Title");

            Forum forum = ForumService.GetById(forumId);
            ForumPermissionManager forumPermissionManager = PermissionManager.CreateForumPermissionManager(forum);

            if (!forumPermissionManager.Read)
            {
                DieMessage(DieMessageType.InsufficientPermissions, "InsufficientPermissions");
            }
            
            currentTemplate = CurrentSession.CurrentTemplate;

            User user = CurrentSession.User;
            int topicsPerPage = PagingTools.GetTopicsPerPage(user);
            int topicCount = TopicService.GetTopicCountInForum(forum);
            int pageCount = PagingTools.GetPageCount(topicCount, topicsPerPage);
            int currentPage = PagingTools.GetPage(Request.QueryString["page"], pageCount);

            MasterPage.TitleGenerator.PageTitle = pageTitle;
            MasterPage.TitleGenerator.ItemName = forum.Name;
            MasterPage.HeaderText = forum.Name;
            MasterPage.AddPathItem(forum.Name, "ViewForum.aspx?forumId=" + forumId);

            if (forumPermissionManager.CreateTopic)
            {
                MasterPage.AddNavigationItem("Templates/Default/Images/Icons/add-topic.gif", "AddTopic.aspx?forumId=" + forumId, "");
            }

            string urlBase = "ViewForum.aspx?forumId=" + forum.Id;
            PagingTools.InitPagers(
                pageCount, currentPage, urlBase,
                TopPager, BottomPager
            );

            TopicRepeater.DataSource = TopicService.GetTopicsByForumPaged(forum, currentPage, topicsPerPage);
            TopicRepeater.DataBind();
        }

        protected void TopicRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Topic topic = e.Item.DataItem as Topic;
                Image topicTypeImage = e.Item.FindControl("TopicTypeImage") as Image;
                topicTypeImage.ImageUrl = UITools.GetTopicTypeImageUrl(topic);
            }
        }

        protected string CurrentTemplate
        {
            get { return currentTemplate; }
            set { currentTemplate = value; }
        }
    }
}
